using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using BlogSystem.Mediator.Mediator;
using BlogSystem.Model.Request;
using BlogSystem.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace BlogSystem.Controller;

/// <summary>
/// 用户 登录注册等 控制器
/// </summary>
[Authorize]
[ApiController]
[Route("v1/api/[controller]")]
public class UserController :ControllerBase
{

   // private readonly IMediator _mediator;
    
    private readonly IUserService _userService;
    public UserController(IUserService userService)
    {
        _userService = userService;
      //  _mediator = mediator;
    }

    /// <summary>
    ///  登录 
    /// </summary>
    /// <param name="loginRequets"></param>
    /// <returns></returns>
    [AllowAnonymous]
    [Route("Login")]
    [HttpPost]
    public async Task<IActionResult> Login(LoginRequets loginRequets)
    {
        var dic =await _userService.Login(loginRequets);
        
        return Ok(new{msg="登录成功",token=dic});
    }
    
    [HttpGet("GetUsersByPage")]
    public async Task<IActionResult> GetUsersByPage([FromQuery] string? keyWord="",[FromQuery] int pageIndex=1,[FromQuery] int pageSize=10)
    {
        
        var articlevo = await _userService.GetUsersByPage(keyWord,pageIndex,pageSize);
        return Ok(new {code="200",msg="成功",total=articlevo.Count(),article=articlevo});
        
    }


    [Route("UserInfo")]
    [HttpGet]
    public async Task<IActionResult> GetSelfInfo()
    {
        
        //第一种从Header中的Token信息反向解析出用户账号，再从数据库中查找返回
        var token = Request.Headers["Authorization"].ToString().Split(" ").Last();
        Console.WriteLine("token:"+token);
        var claimsPrincipal = new JwtSecurityTokenHandler().ReadJwtToken(token);
        var name = claimsPrincipal.Claims.First(claim => claim.Type == "username").Value;
        var user =await _userService.getUserByName(name);
        if (user==null)
        {
            return NotFound("用户信息未找到！");
        }
        return Ok(new {code="200",msg="成功",user=user});

    }
    
    [AllowAnonymous]
    [Route("Register")]
    [HttpPost]
    public async Task<IActionResult> Register(RegisterRequest registerRequest)
    { 
         var res=await _userService.Register(registerRequest);
         return res.Equals(true)?Ok(new { msg = "修改成功" }):NoContent();

    }
    



}